function [estimates, model] = fitExpBound(xdata, ydata)
% [EXTIMATES, MODEL] = FITEXPBOUND(XDATA, YDATA) finds an exponential
% fitting curve for the arguments. The curve has only one degree of freedom
% (lambda: timeconstant). This curve intercepts the YDATA at the end of the
% data. Modified from FITEXP written by ben suter.
% Taro Kiritani, tarokiritani2008@u.northwestern.edu 11/06/2010

% Call fminsearch with a random starting point.
start_point = rand(1);
model = @expfun;
[estimates,fval,exitflag] = fminsearch(model, start_point);
if exitflag ~= 1
    keyboard
end
% expfun accepts curve parameters as inputs, and outputs sse,
% the sum of squares error for A*exp(-lambda*xdata)-ydata,
% and the FittedCurve. FMINSEARCH only needs sse, but we want
% to plot the FittedCurve at the end.
    function [sse, FittedCurve] = expfun(params)
        lambda = params(1);
        FittedCurve = ydata(length(ydata)) .* exp(-lambda * (xdata - xdata(length(xdata))));
        ErrorVector = FittedCurve - ydata;
        sse = sum(ErrorVector .^ 2);
    end
end